package cn.xuqiudong.attachment.dao.mysql;

import cn.xuqiudong.attachment.constant.AttachmentConstant;
import cn.xuqiudong.attachment.dao.BaseAttachmentDao;
import cn.xuqiudong.attachment.model.Attachment;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 描述:
 * @author Vic.xu
 * @since 2022-01-13 10:23
 */
public class MysqlAttachmentDao extends BaseAttachmentDao {


    /**
     * 新增附件
     */
    @Override
    public Attachment insert(Attachment attachment) {
        String sql = "insert into " + AttachmentConstant.ATTACHMENT_TABLE + "(absolute_path, relative_path, temporary, module,content_type, file_size, file_name, original_name,create_time) values (?, ?, 1, ?, ?, ?, ?, ?, now())";
        KeyHolder keyHolder = new GeneratedKeyHolder();

        jdbcTemplate.update(new PreparedStatementCreator() {

            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, attachment.getAbsolutePath());
                ps.setString(2, attachment.getRelativePath());
                ps.setString(3, attachment.getModule());
                ps.setString(4, attachment.getContentType());
                ps.setInt(5, attachment.getSize());
                ps.setString(6, attachment.getFilename());
                ps.setString(7, attachment.getOriginalName());
                return ps;
            }
        }, keyHolder);
        attachment.setId(keyHolder.getKey().intValue());
        return attachment;
    }
}
